package com.zlcx.tz.live.web;


import com.zlcx.tz.live.client.UserClient;
import com.zlcx.tz.live.constant.AppEnum;
import com.zlcx.tz.live.constant.ResultStatus;
import com.zlcx.tz.live.vo.ResultVO;
import com.zlcx.tz.live.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AuthorizationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * <p></p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 * @author zl
 * @date Created in 2018/4/15 14:42
 * @version 1.0
 * @copyright: Copyright (c) founders
 */

public class BaseController {

    public <T> ResultVO<T> successState() {

        ResultVO<T> resultVO = new ResultVO<>(ResultStatus.SUCCESS.getCode());
        resultVO.setMessage(ResultStatus.SUCCESS.getTips());

        return resultVO;
    }

    public <T> ResultVO<T> successState(T data) {

        ResultVO<T> resultVO = successState();
        resultVO.setData(data);

        return resultVO;
    }

    public <T> ResultVO<T> successState(T data, String message) {

        ResultVO<T> resultVO = successState();
        resultVO.setMessage(message);
        resultVO.setData(data);

        return resultVO;
    }

    public <T> ResultVO<T> failState(String message) {

        ResultVO<T> resultVO = new ResultVO<>(ResultStatus.FAILED.getCode());
        resultVO.setMessage(message);
        return resultVO;
    }

    public <T> ResultVO<T> failState(ResultStatus status) {

        ResultVO<T> resultVO = new ResultVO<>(status.getCode());
        resultVO.setMessage(status.getInfo());
        return resultVO;
    }

    public <T> ResultVO<T> failState(ResultStatus status, String message) {

        ResultVO<T> resultVO = new ResultVO<>(status.getCode());
        resultVO.setMessage(message);
        return resultVO;
    }

    public <T> ResultVO<T> failState(String message, T data) {

        ResultVO<T> resultVO = failState(message);
        resultVO.setData(data);
        return resultVO;
    }

    //暂时先在放这里，如果后续比较多可以提成一个接口
    public static String getApp(HttpServletRequest request) {
        String app = request.getHeader("app");
        app = Objects.nonNull(app) && AppEnum.postgraduate.name().equals(app) ?
                AppEnum.postgraduate.name() : AppEnum.tongzhuo.name();
        return app;
    }

    /**
     * 没有用户登录的情况下，security会返回anonymousUser
     */
    public static final String ANONYMOUS_USER = "anonymousUser";

    /**
     * 该方法不需要访问其他服务，可以在security中获取到用户的用户名和id
     *
     * @return UserInfoDTO
     */
    public static Long currentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object object = authentication.getPrincipal();

        if (object instanceof String) {
            if (ANONYMOUS_USER.equals(object)) {
                return null;
            }
            String[] strings = ((String) object).split("-");
            if (strings.length == 2) {
                return Long.parseLong(strings[1]);
            } else {
                throw new AuthorizationServiceException("client token无法获取到用户信息！");
            }
        } else {
            try {
                throw new AuthorizationServiceException("没有获取到用户线信息！");
            } catch (AuthenticationException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 该方法会调用微服务tz-user-center来获取用户基本信息
     *
     * @return UserInfoDTO
     */
    protected UserVO currentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object object = authentication.getPrincipal();
        if (object instanceof String) {
            String[] strings = ((String) object).split("-");
            if (strings.length == 2) {
                UserVO userInfoDTO = (UserVO)userClient.getUserInfo(Long.parseLong(strings[1])).getData();
                return userInfoDTO;
            } else {
                throw new AuthorizationServiceException("client token无法获取到用户信息！");
            }
        } else {
            try {
                throw new AuthorizationServiceException("没有获取到用户线信息！");
            } catch (AuthenticationException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public static int compareVersion(String v1, String v2) {
        if (v1.equals(v2)) {
            return 0;
        }
        String[] version1Array = v1.split("[._]");
        String[] version2Array = v2.split("[._]");
        int index = 0;
        int minLen = Math.min(version1Array.length, version2Array.length);
        long diff = 0;

        while (index < minLen
                && (diff = Long.parseLong(version1Array[index])
                - Long.parseLong(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            for (int i = index; i < version1Array.length; i++) {
                if (Long.parseLong(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Long.parseLong(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }


    @Autowired
    private UserClient userClient;


}
